﻿using AutoMapper;
using MediatR;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.DeepProcess
{
    public class VendorEditCommandHandler : IRequestHandler<VendorEditCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Supplier> supplierRepository;
        private readonly IMapper mapper;
        public VendorEditCommandHandler(IBaseRepository<T_Supplier> supplierRepository, IMapper mapper)
        {
            this.supplierRepository = supplierRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(VendorEditCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            var model = mapper.Map<T_Supplier>(request);
            var supplier = supplierRepository.GetAll().FirstOrDefault(x => x.ID == request.ID);
            if (supplier == null)
            {
                result.Message = "设置成功";
                result.Data = await supplierRepository.Add(model);
                return await Task.FromResult(result);
            }
            else 
            {
                result.Message = "修改成功";
                var supplierModel = mapper.Map(request, supplier);
                result.Data = await supplierRepository.Update(supplierModel);
                return await Task.FromResult(result);
            }
        }
    }
}
